﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RiaToDalLinq.ProviderBase
{
    /// <summary>
    /// 
    /// </summary>
    internal static class TypeResolver
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="seqType"></param>
        /// <returns></returns>
        internal static Type GetElementType(Type seqType)
        {
            Type ie = FindEnumerable(seqType);
            if (ie == null) return seqType;
            return ie.GetGenericArguments()[0];
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="seqType"></param>
        /// <returns></returns>
        private static Type FindEnumerable(Type t)
        {
            if (t == null || t == typeof(string))
                return null;

            if (t.IsArray)
                return typeof(IEnumerable<>).MakeGenericType(t.GetElementType());

            if (t.IsGenericType)
            {
                foreach (Type arg in t.GetGenericArguments())
                {
                    Type ienum = typeof(IEnumerable<>).MakeGenericType(arg);

                    if (ienum.IsAssignableFrom(t))
                    {
                        return ienum;
                    }
                }
            }

            Type[] interfaces = t.GetInterfaces();

            if (interfaces != null && interfaces.Length > 0)
            {
                foreach (Type iface in interfaces)
                {
                    Type ienum = FindEnumerable(iface);
                    if (ienum != null) return ienum;
                }
            }

            if (t.BaseType != null && t.BaseType != typeof(object))
            {
                return FindEnumerable(t.BaseType);
            }

            return null;
        }

    }
}
